import path from 'path';
import * as process from 'process';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import { lingui } from '@lingui/vite-plugin';
import { theme as baseTheme } from '@deepfos/theme';
import seeplnIcon from 'vite-plugin-seepln-icon';
import visualizer from 'rollup-plugin-visualizer';
import { name } from './package.json';

const deepfosPrefixWeb = process.env.DEEPFOS_PREFIX_WEB || '';
const base = `${deepfosPrefixWeb}/${name}/`;

export default defineConfig({
  base,
  optimizeDeps: {
    include: ['umi-request', '@lingui/core', 'react-dom'],
  },
  resolve: {
    alias: {
      '@/': `${path.resolve(process.cwd(), 'src')}/`,
      'ahooks/es/useRequest': '@ahooksjs/use-request',
      lodash: 'lodash-es',
      'lodash.debounce': 'lodash-es/debounce',
      'lodash.throttle': 'lodash-es/throttle',
      classnames: 'clsx',

      ...(process.env.NODE_ENV === 'production' && {
        '@deepfos/fetch': '@deepfos/fetch2',
      }),
    },
  },
  define: {
    'process.env.PACT_ENV': JSON.stringify('production'),
    'process.env.DEEPFOS_PREFIX_WEB': JSON.stringify(deepfosPrefixWeb),
    'process.env.DEEPFOS_PREFIX_SERVER': JSON.stringify(
      process.env.DEEPFOS_PREFIX_SERVER || '/deepfos-server',
    ),
  },
  css: {
    preprocessorOptions: {
      less: {
        modifyVars: {
          ...baseTheme,
          theme: 'variable',
          '@primary-color': '#555fff',

          '@ant-prefix': 'ant4-23',
        },
        javascriptEnabled: true,
      },
    },
  },
  plugins: [
    react({
      plugins: [['@lingui/swc-plugin', {}]],
    }),
    lingui(),
    seeplnIcon(),
  ],
  build: {
    target: ['chrome89'],
    rollupOptions: {
      external: [
        '@deepfos/fetch2',
        '@deepfos/nav-title',
        '@deepfos/request2',
        '@deepfos/store',
        'ahooks',
        'lodash',
        'moment',
        'react',
        'react-dom',
        'react-intl',
        'styled-components',
        'swr',
        'eventemitter2',
        'antd',
      ],
      input: ['src/main.tsx'],
      output: {
        format: 'system',
        dir: 'dist',
        entryFileNames: 'main.js',
      },
      preserveEntrySignatures: 'allow-extension',
      plugins: [
        // importPlugin({
        //   libraryName: 'antd',
        //   style: true,
        // }),
        // importPlugin({
        //   libraryName: 'ahooks',
        //   libraryDirectory: 'es',
        //   camel2DashComponentName: false,
        //   transformToDefaultImport: true,
        // }),
        visualizer(),
      ],
    },
  },
  server: {
    proxy: {
      ...Object.fromEntries(
        ['/deepfos-server', '/package-'].map((address) => [
          address,
          {
            target: 'https://cloud.deepfos.com',
            changeOrigin: true,
            secure: false,
            cookieDomainRewrite: '',
          },
        ]),
      ),
    },
  },
});
